//
//  BRBorrowManager.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/13.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRBorrowManager.h"

#define kQueryTime 10.0

@interface BRBorrowManager ()

@property (nonatomic, strong) dispatch_source_t timer;


@end

@implementation BRBorrowManager

- (instancetype)share {
    
    static BRBorrowManager *man = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        man = [[BRBorrowManager alloc] init];
    });
    return man;
}

// 查询订单
- (void)queryOrder:(void(^)(NSDictionary * _Nonnull resDic))response {
    
    [[BRRequestManager shared] GET:@"" params:nil succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        if (response) {
            response(dataDict);
        }
        // 如果有租借中的订单
//        if (datedic) {
//            WS(weakSelf);
//            [self startQueryTime:^{
//                [weakSelf queryOrder:^(NSDictionary * _Nonnull resDic) {
//
//                }];
//            }];
//        }
        
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        [self cancelTimer];
    }];
}

///取消轮训定时器
- (void)cancelTimer {
    
    if (self.timer) {
        dispatch_source_cancel(self.timer);
        self.timer = nil;
    }
}

///增加轮训定时刷新订单金额
- (void)startQueryTime:(void(^)(void))handler byStatus:(BROrderStatus)status {
    
    if (self.status != status) {
        [self cancelTimer];
        self.status = status;
    }
    
    if (self.timer) return;
    
//    WS(weakSelf);
    //获得队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    //创建一个定时器
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置开始时间
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC));
    //设置时间间隔
    uint64_t interval = (uint64_t)(kQueryTime * NSEC_PER_SEC);
    //设置定时器
    dispatch_source_set_timer(self.timer, start, interval, 0);
    //设置回调
    dispatch_source_set_event_handler(self.timer, ^{
        // 每次需要处理的事
        if (handler) {
            handler();
        }
        
    });
    //由于定时器默认是暂停的所以我们启动一下
    //启动定时器
    dispatch_resume(self.timer);
}

@end
